package com.example.shopping.controller;


import com.example.shopping.dto.CartItem;
import com.example.shopping.entity.Category;
import com.example.shopping.entity.Goods;
import com.example.shopping.entity.User;
import com.example.shopping.service.CartService;
import com.example.shopping.service.CategoryService;
import com.example.shopping.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CartService cartService;

    @GetMapping("/goods/{id}")
    public String goods(@PathVariable int id, Model model, HttpSession session) {
        //通过id拿到数据
        Goods good = goodsService.findById(id);
        if (good != null) {
            List<Category> categories = categoryService.getAll();
            User user = (User) session.getAttribute("loginUser");
            if (user != null) {
                List<CartItem> cartItems = cartService.getCar(user.getId());
                model.addAttribute("cartItems", cartItems);
                model.addAttribute("cartCount", cartItems.size());
            }

            model.addAttribute("categories", categories);
            model.addAttribute("goods", good);
            return "goods_view";
        } else {
            //没有找到商品
            return "error";
        }

    }


}
